﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TvGuide.UI.Models;
using TVGuide.DataAccess.Common;
using TVGuide.Common;
using System.IO;

namespace TvGuide.UI.Controllers
{
    public class SearchController : BaseController
    {
       
        // GET: /Search/

        private SearchData sd;
        private int lang;
        public ActionResult ShowResults(string lng, string query, int? exact)
        {
            this.lang = Utils.LanguageSelect(lng);
            ViewData["lng"] = lng;
            sd = new SearchData(lang);
            
            query = query.Replace('-', '+').Replace('_', '/');
            query = Utils.DecodeFromBase64String(query);
            LogQueryToFile(query);

            sd.SplitChar(query);   

            if (exact==1)
            {
                sd.searchExactProgram(query);
            }
            else
            {
                sd.searchSugesstedPrograms(query);
            }
            
            return View(sd);
        }

        [HttpPost]
        public ActionResult AdvanceSearch(string SearchText, string StartDateText, string EndDateText, List<bool> testcat, string lng)
        {
            if (string.IsNullOrEmpty(lng))
                lng = "arm";

            this.lang = Utils.LanguageSelect(lng);
            sd = new SearchData(lang);

            DateTime startDate;
            DateTime endDate;
            sd.normalizeDates(StartDateText, EndDateText, out startDate, out endDate);
            List<short> catArr = sd.getCatArray(testcat);
            if (String.IsNullOrEmpty(SearchText))
                SearchText = "";
            sd.searchProgram(SearchText.Equals("Որոնել հաղորդում...") ? "":SearchText, startDate, endDate, catArr.ToArray());
            sd.StartDateText = StartDateText;
            sd.EndDateText = EndDateText;
            ViewData["lng"] = lng;
            return View("AdvanceSearch",sd);
        }

        public SearchData GetProgsForTheEvening(short catID)
        {
            DateTime today = DateTime.Today;
            if (!(today.Day ==DateTime.Now.AddHours(Utils.ZoneHour).Day))
            {
                today = today.AddDays(1);
            }
            today = today.AddHours(18); // Evening 18:00
            sd.searchProgram("", today, today.AddHours(5), new short[] { catID });
            return  sd;
        }

        public ActionResult GetFilmForTheEvening(string lng)
        {
            ViewData["lng"] = lng;
            ViewData["armlink"] = "/arm/Search/GetFilmForTheEvening";
            ViewData["englink"] = "/eng/Search/GetFilmForTheEvening"; 
            this.lang = Utils.LanguageSelect(lng);
            sd = new SearchData(lang);
            sd = GetProgsForTheEvening((short)TVGuide.Enums.Categories.FILMS);
            return View("AdvanceSearch", sd);
        }

        public ActionResult GetSportForTheEvening(string lng)
        {
            ViewData["lng"] = lng;
            ViewData["armlink"] = "/arm/Search/GetSportForTheEvening";
            ViewData["englink"] = "/eng/Search/GetSportForTheEvening"; 
            this.lang = Utils.LanguageSelect(lng);
            sd = new SearchData(lang);
            sd = GetProgsForTheEvening((short)TVGuide.Enums.Categories.SPORT);
            return View("AdvanceSearch", sd);
        }

        public ActionResult GetHumorForTheEvening(string lng)
        {
            ViewData["lng"] = lng;
            ViewData["armlink"] = "/arm/Search/GetHumorForTheEvening";
            ViewData["englink"] = "/eng/Search/GetHumorForTheEvening"; 
            this.lang = Utils.LanguageSelect(lng);
            sd = new SearchData(lang);
            sd = GetProgsForTheEvening((short)TVGuide.Enums.Categories.HUMOR);
            return View("AdvanceSearch", sd);
        }

        public ActionResult GetSoapForTheEvening(string lng)
        {
            ViewData["lng"] = lng;
            ViewData["armlink"] = "/arm/Search/GetSoapForTheEvening";
            ViewData["englink"] = "/eng/Search/GetSoapForTheEvening"; 
            this.lang = Utils.LanguageSelect(lng);
            sd = new SearchData(lang);
            sd = GetProgsForTheEvening((short)TVGuide.Enums.Categories.SOAP);
            return View("AdvanceSearch", sd);
        }

        public ActionResult Advance(string lng)
        {
            ViewData["lng"] = lng;
            ViewData["armlink"] = "/arm/Search/Advance";
            ViewData["englink"] = "/eng/Search/Advance"; 
            this.lang = Utils.LanguageSelect(lng);
            sd = new SearchData(lang);
            return View("AdvanceSearch",sd);
        }

        public JsonResult GetJSONResults(string query)
        {
            if (sd == null)
                sd = new SearchData(1);
            List<string> autocompleteList = sd.getAutocompleteList(query);
            return Json(autocompleteList, JsonRequestBehavior.AllowGet);
        }

        private void LogQueryToFile(string logMessage)
        {
            string filePath = Server.MapPath("/dev/==SecureAppDataSecure==/query_log.txt");
            try
            {
                using (StreamWriter w = System.IO.File.AppendText(filePath))
                {
                    Log(logMessage, w);
                    // Close the writer and underlying file.
                    w.Close();
                }
            }
            catch
            {
            }
            // Open and read the file.
        }

        private void Log(string logMessage, TextWriter w)
        {
            string ip = Request.ServerVariables["REMOTE_ADDR"];
            w.Write("\r\nLog Entry : ");
            w.WriteLine("{0} {1}", DateTime.Now.AddHours(Utils.ZoneHour).ToLongTimeString(),
                DateTime.Now.AddHours(Utils.ZoneHour).ToLongDateString());
            w.WriteLine(" :");
            w.WriteLine("{1} => {0} ", logMessage, ip);
            w.WriteLine("-------------------------------");
            // Update the underlying file.
            w.Flush();
        }
       
    }
}
